package com.apobates.forum.grief.lang.mapper;

import com.apobates.forum.grief.lang.ResponseResult;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * 响应结果的REST映射函数
 * jersey(2.30.x)
 * @param <T>
 */
public class RestResponseResultMapper<T> implements ResponseResultMapper<T, Response> {
    private final MediaType type;

    /**
     * json
     */
    private final static MediaType JSON = MediaType.APPLICATION_JSON_TYPE;
    /**
     * 文本
     */
    private final static MediaType TEXT = MediaType.TEXT_PLAIN_TYPE;
    /**
     * json格式结果转换器
     */
    public final static RestResponseResultMapper JSON_TYPE = new RestResponseResultMapper<>(JSON);
    /**
     * 文本格式结果转换器
     */
    public final static RestResponseResultMapper TEXT_TYPE = new RestResponseResultMapper(TEXT);

    private RestResponseResultMapper(MediaType mediaType) {
        this.type = mediaType;
    }

    @Override
    public Response map(ResponseResult<T> result) {
        return to(type, result);
    }

    private Response to(MediaType type, ResponseResult<T> result){
        return Response
                .status(result.getCode())
                .entity(result.getEntity())
                .type(type)
                .build();
    }

    public static void main(String[] args) {
        Response res = RestResponseResultMapper.JSON_TYPE.map(ResponseResult.notFound());
        if(null!=res && null!=res.getEntity()) {
            System.out.println(res.getEntity().toString());
        }else {
            System.out.println("500");
        }
    }
}
